<template>
  <view
    class="container"
    :style="{ paddingBottom: !pageDisabled ? '150rpx' : '0' }"
  >
    <view class="note-section" v-if="examineShow">
      <view style="display: flex">
        <up-button
          text="通过"
          type="primary"
          style="margin-right: 20rpx"
          @click="handlePass"
        />
        <up-button text="驳回" type="error" @click="handleReject" />
      </view>
      <up-textarea
        v-model="form.auditInstructions"
        placeholder="驳回时请填写审核说明"
        style="margin-top: 10rpx"
      ></up-textarea>
    </view>
    <view class="form-card">
      <up-form
        :model="form"
        :rules="rules"
        ref="formRef"
        labelPosition="left"
        labelWidth="160rpx"
      >
        <up-form-item
          :required="true"
          prop="change_code"
          label="单据编码"
          class="border-bottom"
        >
          <up-input
            v-model="form.change_code"
            placeholder="系统自动生成"
            readonly
            border="none"
            placeholder-class="codePlaceholder"
          ></up-input>
        </up-form-item>
        <up-form-item label="单据名称" prop="change_name" class="border-bottom">
          <up-input
            v-model="form.change_name"
            placeholder="请输入单据名称"
            :readonly="pageDisabled"
            border="none"
          />
        </up-form-item>
        <up-form-item
          label="变更人"
          prop="change_user"
          class="border-bottom"
          @click="handleUserAdmin('change_user')"
        >
          <view @click.self="handleUserAdmin('change_user')">
            <up-input
              v-model="user.change_user"
              placeholder="请选择变更人"
              border="none"
              :readonly="pageDisabled"
            ></up-input>
          </view>
          <template #right>
            <up-icon name="arrow-right"></up-icon>
          </template>
        </up-form-item>
        <up-form-item label="变更日期" prop="change_date" class="border-bottom">
          <uni-datetime-picker
            type="date"
            placeholder="请选择日期"
            clear-icon
            v-model="form.change_date"
            :class="{ 'date-color': !form.change_date }"
            :border="false"
            :disabled="pageDisabled"
            class="datetime-color"
          />
        </up-form-item>
				<up-form-item
				  label="变更原因"
				  prop="change_reason"
				  class="border-bottom"
				>
				  <up-input
				    v-model="form.change_reason"
				    placeholder="请输入变更原因"
				    :readonly="pageDisabled"
				    border="none"
				  />
				</up-form-item>
        <view class="more" @click="handleMore"
          >{{ display ? "收起变更内容" : "展开变更内容"
          }}<up-icon :name="display ? 'arrow-up' : 'arrow-down'"
        /></view>
        <view class="display" v-if="display">
          <up-form-item
            label="资产分类"
            prop="asset_category"
            class="border-bottom"
            @click="handleAssetCategory"
          >
            <view @click.self="handleAssetCategory">
              <up-input
                v-model="assetCategory.name"
                placeholder="请选择资产分类"
                border="none"
                :readonly="pageDisabled"
              ></up-input>
            </view>
            <template #right>
              <up-icon name="arrow-right"></up-icon>
            </template>
          </up-form-item>
					<up-form-item
					  prop="asset_name"
					  label="资产名称"
					  class="border-bottom"
					>
					  <up-input
					    v-model="form.asset_name"
					    placeholder="请输入资产品牌"
					    border="none"
					    :readonly="pageDisabled"
					  ></up-input>
					</up-form-item>
					<up-form-item
					  label="管理员"
					  prop="asset_admin"
					  class="border-bottom"
					  @click="handleUserAdmin('asset_admin')"
					>
					  <view @click.self="handleUserAdmin('asset_admin')">
					    <up-input
					      v-model="user.asset_admin"
					      placeholder="请选择管理员"
					      border="none"
					      :readonly="pageDisabled"
					    ></up-input>
					  </view>
					  <template #right>
					    <up-icon name="arrow-right"></up-icon>
					  </template>
					</up-form-item>
					<up-form-item
					  label="使用人"
					  prop="user"
					  class="border-bottom"
					  @click="handleUserAdmin('user')"
					>
					  <view @click.self="handleUserAdmin('user')">
					    <up-input
					      v-model="user.user"
					      placeholder="请选择使用人"
					      border="none"
					      :readonly="pageDisabled"
					    ></up-input>
					  </view>
					  <template #right>
					    <up-icon name="arrow-right"></up-icon>
					  </template>
					</up-form-item>
					<up-form-item
					  label="存放位置"
					  prop="location"
					  class="border-bottom"
					  @click="handleLocation"
					>
					  <view @click.self="handleLocation">
					    <up-input
					      v-model="location.name"
					      placeholder="请选择存放位置"
					      border="none"
					      :readonly="pageDisabled"
					    ></up-input>
					  </view>
					  <template #right>
					    <up-icon name="arrow-right"></up-icon>
					  </template>
					</up-form-item>
					<up-form-item
					  label="使用部门"
					  prop="department"
					  class="border-bottom"
					  @click="handleDepartment"
					>
					  <view @click.self="handleDepartment">
					    <up-input
					      v-model="department.name"
					      placeholder="请选择使用部门"
					      border="none"
					      :readonly="pageDisabled"
					    ></up-input>
					  </view>
					  <template #right>
					    <up-icon name="arrow-right"></up-icon>
					  </template>
					</up-form-item>
          <up-form-item
            label="采购日期"
            prop="purchase_date"
            class="border-bottom"
          >
            <uni-datetime-picker
              type="date"
              placeholder="请选择日期"
              clear-icon
              v-model="form.purchase_date"
              :class="{ 'date-color': !form.purchase_date }"
              :border="false"
              :disabled="pageDisabled"
              class="datetime-color"
            />
          </up-form-item>
          <up-form-item
            label="有效期"
            prop="expiration_date"
            class="border-bottom"
          >
            <uni-datetime-picker
              type="date"
              placeholder="请选择日期"
              clear-icon
              v-model="form.expiration_date"
              :class="{ 'date-color': !form.expiration_date }"
              :border="false"
              :disabled="pageDisabled"
              class="datetime-color"
            />
          </up-form-item>
          <up-form-item
            prop="spec_model"
            label="规格型号"
            class="border-bottom"
          >
            <up-input
              v-model="form.spec_model"
              placeholder="请输入规格型号"
              :readonly="pageDisabled"
              border="none"
            ></up-input>
          </up-form-item>
          <up-form-item prop="brand" label="资产品牌" class="border-bottom">
            <up-input
              v-model="form.brand"
              placeholder="请输入资产品牌"
              border="none"
              :readonly="pageDisabled"
            ></up-input>
          </up-form-item>
          <up-form-item prop="unit" label="计量单位" class="border-bottom">
            <up-input
              v-model="form.unit"
              placeholder="请输入计量单位"
              :readonly="pageDisabled"
              border="none"
            ></up-input>
          </up-form-item>
					<up-form-item label="附件" class="border-bottom">
					  <view style="display: flex; width: 100%; flex-direction: column">
					    <up-button
					      style="flex: 1"
					      type="primary"
					      v-if="!pageDisabled"
					      @click="selectFile"
					      >点击上传文件</up-button
					    >
					    <!-- 已选文件展示 -->
					    <view
					      v-if="attachmentsUpload[0].files.length"
					      style="margin-top: 10rpx; flex: 1"
					    >
					      已上传文件：
					      <view
					        v-for="items in attachmentsUpload[0].files"
					        :key="items.id"
					        style="display: flex"
					      >
					        <text style="color: red" @click="handleDownFile(items)">
					          {{ items.name }}
					        </text>
					        <up-icon
					          v-if="!pageDisabled"
					          @click="handleClose(items)"
					          name="close"
					          color="#ccc"
					        />
					      </view>
					    </view>
					  </view>
					</up-form-item>
        </view>
      </up-form>
    </view>
    <view class="note-section">
      <up-form-item label="备注" prop="remark" labelPosition="top">
        <up-textarea
          v-model="form.remark"
          placeholder="要留下点什么吗"
          style="margin-top: 10rpx"
          :disabled="pageDisabled"
        ></up-textarea>
      </up-form-item>
    </view>
    <view class="asset-list">
      <view class="list-header">
        <text>资产列表</text>
        <text class="count">共计: {{ assetDataList.length }}</text>
      </view>

      <view class="asset-item" v-for="item in assetDataList" :key="item.id">
        <!-- 左侧信息 -->
        <view class="asset-right-container">
          <up-image
            :src="getImage(item.image)"
            width="160rpx"
            height="160rpx"
          />
          <view class="status">
            <up-tag
              v-if="item.assetStateName"
              :text="item.assetStateName"
              size="mini"
            />
          </view>
        </view>
        <view class="asset-info">
          <view class="asset-name">{{ item.asset_name }}</view>
          <view class="info">使用部门：{{ item.department_name }}</view>
          <view class="info">资产管理员：{{ item.asset_admin_name }}</view>
          <view class="info">存放地点：{{ item.location_name }}</view>
          <view class="info">资产编码：{{ item.asset_code }}</view>
          <view class="info">RFID编码：{{ item.label_number }}</view>
        </view>
        <up-icon
          name="minus-circle"
          size="22"
          v-if="!pageDisabled"
          color="#f00"
          @click="handleDelete(item)"
        />
      </view>
    </view>

    <view class="footer-buttons" v-if="!pageDisabled">
      <up-button
        type="primary"
        :customStyle="{
          'margin-right': '20rpx',
        }"
        @click="handleAddList"
        >添加</up-button
      >
      <up-button type="primary" @click="handleSave">提交</up-button>
    </view>
  </view>

  <!-- 选人 -->
  <up-action-sheet
    :show="user.show"
    :actions="user.actions"
    title="请选择"
    @close="user.show = false"
    @select="userSelect"
  >
  </up-action-sheet>

  <!-- 选变更日期 -->
  <up-datetime-picker
    v-model="date.model"
    :show="date.show"
    mode="date"
    @confirm="onDateConfirm"
    @cancel="date.show = false"
    :formatter="formatter"
  ></up-datetime-picker>

  <!-- 选存放位置 -->
  <up-action-sheet
    :show="location.show"
    :actions="location.actions"
    title="请选择"
    @close="location.show = false"
    @select="locationSelect"
  >
  </up-action-sheet>

  <!-- 选部门 -->
  <up-action-sheet
    :show="department.show"
    :actions="department.actions"
    title="请选择"
    @close="department.show = false"
    @select="departmentSelect"
  >
  </up-action-sheet>

  <!-- 选资产分类 -->
  <up-action-sheet
    :show="assetCategory.show"
    :actions="assetCategory.actions"
    title="请选择"
    @close="assetCategory.show = false"
    @select="assetCategorySelect"
  >
  </up-action-sheet>

  <!-- 选采购日期 -->
  <up-datetime-picker
    v-model="purchaseDate.model"
    :show="purchaseDate.show"
    mode="date"
    @confirm="onPurchaseDateConfirm"
    @cancel="purchaseDate.show = false"
    :formatter="formatter"
  ></up-datetime-picker>

  <!-- 选有效期 -->
  <up-datetime-picker
    v-model="expirationDate.model"
    :show="expirationDate.show"
    mode="date"
    @confirm="onExpirationDateConfirm"
    @cancel="expirationDate.show = false"
    :formatter="formatter"
  ></up-datetime-picker>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import {
  generateUUID,
  formatter,
  formatTimestamp,
  formatDateTime,
} from "@/utils";
import http, { BASE_URL } from "@/api/request";
import { t } from "@/locale/index.js";
import fileSys from "@/utils/fileSys";

const pageId = ref("");
const formRef = ref(null);

const enumList = [
  { code: "getviewTable", name: "Sys_GetUserNameById" },
  { code: "getviewTable", name: "getAssetAddressList" },
  { code: "getviewTable", name: "Sys_GetGroupNameById" },
  { code: "getviewTable", name: "getAssetClassList" },
];
const display = ref(true);
const form = ref({
  change_code: "",
  change_name: "",
  change_user: "",
  change_reason: "",
  user: "",
  location: "",
  remark: "",
  asset_category: "",
  purchase_date: "",
  expiration_date: "",
  spec_model: "",
  brand: "",
  unit: "",
  asset_name: "",
});
const user = reactive({
  actions: [],
  change_user: "",
  asset_admin: "",
  user: "",
  show: false,
  name: "",
});

const location = reactive({
  show: false,
  name: "",
  actions: [],
});

const department = reactive({
  show: false,
  name: "",
  actions: [],
});

const date = reactive({
  show: false,
  model: Date.now(),
});

const assetCategory = reactive({
  show: false,
  name: "",
  actions: [],
});

const purchaseDate = reactive({
  show: false,
  model: Date.now(),
});

const expirationDate = reactive({
  show: false,
  model: Date.now(),
});

const assetDataList = ref([]);
const copyDataList = ref([]);
const pageDisabled = ref(false);
const examineShow = ref(false);
const state = ref("");

onLoad(async (query) => {
  await getDataList();
  const data = uni.getStorageSync("assetInfoData");
  state.value = query.name;
  // 获取页面信息
  await getPageInfo();
  if (query.name === "add") {
    uni.setNavigationBarTitle({
      title: t("assetchangeorder.add"),
    });
    examineShow.value = false;
    pageDisabled.value = false;
  } else if (query.name === "edit") {
    uni.setNavigationBarTitle({
      title: t("assetchangeorder.edit"),
    });
    form.value = data;
    pageDisabled.value = false;
    await getAssetBorrowList(query.changeCode);
  } else if (query.name === "detail") {
    uni.setNavigationBarTitle({
      title: t("assetchangeorder.detail"),
    });
    form.value = data;
    pageDisabled.value = true;
    examineShow.value = false;
    await getAssetBorrowList(query.changeCode);
  } else if (query.name === "examine") {
    uni.setNavigationBarTitle({
      title: t("assetchangeorder.examine"),
    });
    form.value = data;
    pageDisabled.value = true;
    examineShow.value = true;
    await getAssetBorrowList(query.changeCode);
  }
  if (form.value.id) {
    await getFiles();
  }

  user.change_user = user.actions.find(
    (item) => item.value === data?.change_user
  )?.name;
  user.asset_admin = user.actions.find(
    (item) => item.value === data?.asset_admin
  )?.name;
  user.user = user.actions.find((item) => item.value === data?.user)?.name;
  location.name = location.actions.find(
    (item) => item.value === data?.location
  )?.name;
  department.name = department.actions.find(
    (item) => item.value === data?.department
  )?.name;
  assetCategory.name = assetCategory.actions.find(
    (item) => item.value === data?.asset_category
  )?.name;
});

const attachmentsUpload = ref([
  {
    Fileld: [],
    files: [],
    linkId: "1",
    taskId: "<%assetchangemstr.id%>",
  },
]);

const getFiles = async () => {
  const postData = {
    linkId: "1",
    taskId: form.value.id,
  };
  const { code, isSuccess, result } = await http.post(
    "/api/file/GetTaskLinkedFiles",
    postData
  );
  if (code && isSuccess && result) {
    result.forEach((item) => {
      attachmentsUpload.value[0].files.push({
        id: item.id,
        name: item.fileName + "  " + item.userName + "  " + item.creationTime,
        url: `/File/Download?fileId=` + item.id,
      });
    });
  }
};

const getPageInfo = async () => {
  const data = {
    assetlist: "assetchange",
    pageCode: "assetchangeadd",
  };

  const { code, isSuccess, result } = await http.post(
    "/api/page/GetPageInfoByCode",
    data
  );
  if (code && isSuccess) {
    pageId.value = result.page.parentPageId;
  }
};

onUnload(() => {
  uni.removeStorageSync("assetInfoData");
});
function camelToSnake(str) {
  return str.replace(/([A-Z])/g, "_$1").toLowerCase();
}

function convertKeysToSnakeCase(obj) {
  if (Array.isArray(obj)) {
    return obj.map(convertKeysToSnakeCase);
  } else if (obj !== null && typeof obj === "object") {
    return Object.entries(obj).reduce((acc, [key, value]) => {
      const newKey = camelToSnake(key);
      acc[newKey] = convertKeysToSnakeCase(value);
      return acc;
    }, {});
  } else {
    return obj;
  }
}

const getAssetBorrowList = async (changeCode) => {
  const data = {
    appPageId: pageId.value,
    appPageCode: "",
    dataSourceCode: "getAssetList",
    filters: [{ name: "change_code", value: changeCode }],
    is_search_column_all: true,
  };
  const { code, isSuccess, result } = await http.post(
    "/api/module/GetDataWithDataSource",
    data
  );
  if (code && isSuccess) {
    assetDataList.value = result.data.map((item) => item.assetchangedet);
    copyDataList.value = JSON.parse(
      JSON.stringify(assetDataList.value.map((item) => ({ ...item })))
    );
  }
};

onMounted(() => {
  uni.$on("assetSelected", handleAssetSelected);
});

onBeforeUnmount(() => {
  uni.$off("assetSelected", handleAssetSelected);
});

function toCamelCase(str) {
  return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}

// function convertKeysToCamelCase(obj) {
//   const newObj = {};
//   for (const key in obj) {
//     const camelKey = toCamelCase(key);
//     newObj[camelKey] = obj[key];
//   }
//   return newObj;
// }

const handleAssetSelected = (data) => {
  data.forEach((item) => {
    const isDuplicate = assetDataList.value.some(
      (existingItem) => existingItem.id === item.id
    );
    if (!isDuplicate) {
      assetDataList.value.push(item);
    }
  });
};

const handlePass = async () => {
  uni.showLoading({
    title: "操作中...",
  });
  const data = {
    pageCode: "assetchange",
    params: {
      args: [
        {
          name: "interfaceCode",
          value: "assetchange.auditAssetChangeOrder",
        },
        {
          name: "changeCode",
          value: form.value.change_code,
        },
        {
          name: "auditState",
          value: "APPROVED",
        },
      ],
    },
    methodName: "auditAssetChangeOrder",
  };
  try {
    const { code, isSuccess } = await http.post("/api/module/Invoke", data);

    if (code && isSuccess) {
      uni.showToast({
        title: "通过",
        icon: "success",
      });
      uni.navigateBack();
    } else {
      uni.showToast({
        title: "失败",
        icon: "error",
      });
    }
  } catch {
    uni.showToast({
      title: "失败",
      icon: "error",
    });
  }
  uni.hideLoading();
};

const handleReject = async () => {
  uni.showLoading({
    title: "操作中...",
  });
  const data = {
    pageCode: "assetchange",
    params: {
      args: [
        {
          name: "interfaceCode",
          value: "assetchange.auditAssetChangeOrder",
        },
        {
          name: "changeCode",
          value: form.value.change_code,
        },
        {
          name: "auditState",
          value: "REJECTED",
        },
        {
          name: "auditInstructions",
          value: form.value.auditInstructions,
        },
      ],
    },
    methodName: "auditAssetChangeOrder",
  };
  try {
    const { code, isSuccess } = await http.post("/api/module/Invoke", data);

    if (code && isSuccess) {
      uni.showToast({
        title: "驳回成功",
        icon: "success",
      });
      uni.navigateBack();
    } else {
      uni.showToast({
        title: "失败",
        icon: "error",
      });
    }
  } catch {
    uni.showToast({
      title: "失败",
      icon: "error",
    });
  }
  uni.hideLoading();
};

const hideKeyboard = () => {
  uni.hideKeyboard();
};

const handleAddList = () => {
  uni.navigateTo({
    url: "/components/assetsAddList/index",
  });
};

// 获取资产列表
const getDataList = async () => {
  const batchRequests = enumList.map((item) => {
    const params = [
      {
        id: generateUUID(),
        service: "Module",
        method: item.code,
        param: JSON.stringify({ code: item.name, filters: [] }),
      },
    ];

    return http.post("/api/module/GetBatchResult", params).then((res) => ({
      ...res,
      name: item.name,
    }));
  });

  try {
    const results = await Promise.all(batchRequests);

    results.forEach(({ name, result, isSuccess, code }) => {
      if (!isSuccess || !code) return;
      switch (name) {
        case "Sys_GetUserNameById":
          user.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.text,
              value: item.id,
            };
          });
          break;
        case "getAssetAddressList":
          location.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.asset_address_name,
              value: item.asset_address_code,
            };
          });
          break;
        case "Sys_GetGroupNameById":
          department.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.text,
              value: item.id,
            };
          });
          break;
        case "getAssetClassList":
          assetCategory.actions = result[0].response.data.viewTable.map(
            (item) => {
              return {
                ...item,
                name: item.asset_class_name,
                value: item.asset_class_code,
              };
            }
          );
          break;
      }
    });
  } catch (error) {
    console.error("获取枚举失败:", error);
  }
};

const handleUserAdmin = (name) => {
  user.name = name;
  if (!pageDisabled.value) {
    user.show = true;
    hideKeyboard();
  }
};

const userSelect = (e) => {
  if (user.name === "change_user") {
    form.value.change_user = e.value;
    user.change_user = e.name;
  }
  if (user.name === "asset_admin") {
    form.value.asset_admin = e.value;
    user.asset_admin = e.name;
  }

  if (user.name === "user") {
    form.value.user = e.value;
    user.user = e.name;
  }
};

const handleDate = () => {
  if (!pageDisabled.value) {
    date.show = true;
    hideKeyboard();
  }
};

const onDateConfirm = (e) => {
  form.value.change_date = formatTimestamp(e.value, false);
  date.show = false;
};

const handleLocation = () => {
  if (!pageDisabled.value) {
    location.show = true;
    hideKeyboard();
  }
};

const locationSelect = (e) => {
  form.value.location = e.value;
  location.name = e.name;
};

const handleDepartment = () => {
  if (!pageDisabled.value) {
    department.show = true;
    hideKeyboard();
  }
};

const departmentSelect = (e) => {
  form.value.department = e.value;
  department.name = e.name;
};

const handleAssetCategory = () => {
  if (!pageDisabled.value) {
    assetCategory.show = true;
    hideKeyboard();
  }
};

const assetCategorySelect = (e) => {
  form.value.asset_category = e.value;
  assetCategory.name = e.name;
};

const handlePurchaseDate = () => {
  if (!pageDisabled.value) {
    purchaseDate.show = true;
    hideKeyboard();
  }
};

const onPurchaseDateConfirm = (e) => {
  form.value.purchase_date = formatTimestamp(e.value, false);
  purchaseDate.show = false;
};

const handleExpirationDate = () => {
  if (!pageDisabled.value) {
    expirationDate.show = true;
    hideKeyboard();
  }
};

const onExpirationDateConfirm = (e) => {
  form.value.expiration_date = formatTimestamp(e.value, false);
  expirationDate.show = false;
};

const getImage = (image) => {
  const type = getItemType(image);
  if (image) {
    if (type === "ID") {
      return `${BASE_URL}/File/GetImage?fileId=${image}`;
    } else {
      return image;
    }
  }
  return "";
};

const getItemType = (item) => {
  const idPattern = /^[a-zA-Z0-9-]+$/; // 包含字母、数字和 - 符号
  const apiPattern = /^\/File\//; // 假设接口地址以 '/File/' 开头
  const pathPattern = /^\/(?!File)/; // 普通路径以 '/' 开头，但不以 '/File/' 开头
  const relativePathPattern = /^[^/]/; // 假设相对路径不以 '/' 开头

  if (idPattern.test(item)) {
    return "ID";
  } else if (apiPattern.test(item)) {
    return "接口"; // 识别接口地址
  } else if (pathPattern.test(item)) {
    return "路径"; // 识别普通路径
  } else if (relativePathPattern.test(item)) {
    return "相对路径"; // 识别相对路径
  } else {
    return "其他";
  }
};

const handleDelete = (item) => {
  assetDataList.value = assetDataList.value.filter(
    (items) => item.id !== items.id
  );
};

function diffArraysById(newList, oldList, key = "det_id") {
  const newMap = new Map(newList.map((item) => [item[key], item]));
  const oldMap = new Map(oldList.map((item) => [item[key], item]));

  const added = newList.filter((item) => !oldMap.has(item[key]));
  const removed = oldList.filter((item) => !newMap.has(item[key]));

  let isSame = added.length === 0 && removed.length === 0;

  if (isSame) {
    for (const [id, newItem] of newMap.entries()) {
      const oldItem = oldMap.get(id);
      if (JSON.stringify(newItem) !== JSON.stringify(oldItem)) {
        isSame = false;
        break;
      }
    }
  }

  return { added, removed, isSame };
}

const handleSave = async () => {
  uni.showLoading({
    title: "提交中...",
  });
  if (state.value === "add" && form.value.id) {
    delete form.value.id;
  }
  const rawData = {
    ...form.value,
    attachment: attachmentsUpload.value?.[0]?.files?.length
      ? attachmentsUpload.value[0].files.map((item) => item.id).join(",")
      : "",
  };

  const dataObjct = Object.fromEntries(
    Object.entries(rawData).filter(
      ([_, value]) => value !== "" && value !== null && value !== undefined
    )
  );
  let data;

  if (state.value === "add") {
    data = {
      pageId: pageId.value,
      methodName: "doSaveTableData",
      saveTableDataRequest: {
        data: {
          insert: {
            assetchangemstr: {
              data: {
                ...dataObjct,
                state: "PENDING_REVIEW",
              },
            },
            assetchangedet: {
              data: assetDataList.value.map((item) => ({
                asset_code: item.asset_code,
              })),
            },
          },
          update: { assetchangedet: { data: [] } },
          remove: {},
          updateWhere: {},
          removeWhere: {},
          otherData: {
            fileAttachments: attachmentsUpload.value,
          },
          savedInvoke: {},
          pageAuths: [],
        },
      },
    };
  } else if (state.value === "edit") {
    const { added, removed, isSame } = diffArraysById(
      assetDataList.value,
      copyDataList.value,
      "det_id"
    );
    console.log(isSame, added, removed);
    data = {
      pageId: pageId.value,
      methodName: "doSaveTableData",
      saveTableDataRequest: {
        data: {
          insert: {
            assetchangedet: {
              data: isSame
                ? []
                : added.map((item) => ({
                    asset_code: item.asset_code,
                  })),
            },
          },
          update: {
            assetchangedet: {
              data: isSame
                ? []
                : removed.map((item) => ({
                    id: item.det_id,
                    is_deleted: 1,
                  })),
            },
            assetchangemstr: {
              ...dataObjct,
              state: "PENDING_REVIEW",
            },
          },
          remove: {},
          updateWhere: {},
          removeWhere: {},
          otherData: {
            fileAttachments: attachmentsUpload.value,
          },
          savedInvoke: {},
          pageAuths: [],
        },
      },
    };
  }

  try {
    const { code, isSuccess, error } = await http.post(
      "/api/module/Invoke",
      data
    );

    if (code && isSuccess) {
      uni.showToast({
        title: "提交成功",
        icon: "success",
      });

      if (state.value === "add") {
        formRef.value?.resetFields(); // 重置校验状态
        form.value = {
          change_code: "",
          change_name: "",
          change_user: "",
          change_reason: "",
          user: "",
          location: "",
          remark: "",
          asset_category: "",
          purchase_date: "",
          expiration_date: "",
          spec_model: "",
          brand: "",
          unit: "",
        };
        user.change_user = "";
        user.asset_admin = "";
        user.user = "";
        user.name = "";
        location.name = "";
        department.name = "";
        assetCategory.name = "";

        assetDataList.value = [];
      }
      attachmentsUpload.value = [
        {
          Fileld: [],
          files: [],
          linkId: "1",
          taskId: "<%assetlistmstr.id%>",
        },
      ];
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
			uni.showModal({
			  title: '提示',
			  content: error || "提交失败",
			  showCancel: false,
			  confirmText: '我知道了'
			});
    }
  } catch {
    uni.showToast({
      title: "提交失败",
      icon: "error",
    });
  }
  uni.hideLoading();
};

const handleMore = () => {
  display.value = !display.value;
};

const selectFile = () => {
  if (attachmentsUpload.value[0].files.length === 10) {
    uni.showLoading({
      title: "超出限制！",
      type: "error",
    });
  } else {
    fileSys().then((res) => {
      const userInfo = JSON.parse(uni.getStorageSync("userInfo"));
      attachmentsUpload.value[0].files.push({
        id: res[0].id,
        name:
          (res[0].fileName || "未知文件") +
          "  " +
          userInfo.name +
          "  " +
          formatDateTime(new Date()),
        url: `/File/Download?fileId=` + res[0].id,
      });
    });
  }
  setTimeout(() => {
    uni.hideLoading();
  }, 1500);
};

const handleDownFile = (items) => {
  uni.downloadFile({
    url: BASE_URL + items.url,
    success: (res) => {
      if (res.statusCode === 200) {
        plus.runtime.openFile(res.tempFilePath, {}, (e) => {
          uni.showModal({
            title: "无法打开文件",
            content: "请安装 WPS Office 或 QQ 浏览器等可打开该文件的应用",
            confirmText: "去安装",
            success: (modalRes) => {
              if (modalRes.confirm) {
                try {
                	plus.runtime.openURL('market://details?id=com.tencent.mtt', () => {
                		plus.runtime.openURL('https://browser.qq.com');
                	});
                } catch (e) {
                	plus.runtime.openURL('https://browser.qq.com');
                }
              }
            },
          });
        });
      }
    },
    fail: (err) => {
      console.error("下载失败", err);
      uni.showToast({ title: "下载失败", icon: "none" });
    },
  });
};

const handleClose = (items) => {
  attachmentsUpload.value[0].files = attachmentsUpload.value[0].files.filter(
    (item) => item.id !== items.id
  );
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  padding-bottom: 150rpx;
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;

  .disabled {
    color: #ccc;
  }
}

.note-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.asset-list {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;

  .list-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
  }

  .asset-item:last-child {
    padding-bottom: 0;
  }

  .asset-item {
    display: flex;
    justify-content: space-between;
    border-top: 1px solid #eee;
    padding: 20rpx 0;
    .asset-right-container {
      position: relative;
      .status {
        position: absolute;
        right: 0;
        top: 0;
      }
    }

    .asset-info {
      flex: 1;
      padding-left: 20rpx;

      .asset-name {
        font-weight: bold;
        font-size: 28rpx;
        margin-bottom: 6rpx;
      }

      .info {
        color: #666;
        font-size: 24rpx;
      }
    }
  }
}

.footer-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
}
.border-bottom {
  border-bottom: 1px solid #f5f5f5;
}
.codePlaceholder {
  color: #000 !important;
}
.more {
  display: flex;
  color: rgb(71, 146, 253);
  font-size: 15px;
  margin: 20rpx 0;
}
:deep(.datetime-color .uni-date__x-input) {
  color: #000 !important;
  opacity: 1 !important;
}
:deep(.date-color .uni-date__x-input) {
  color: #c2c7ce !important;
  opacity: 1 !important;
}
:deep(.uni-date-editor--x__disabled) {
  opacity: 1 !important;
}
</style>
